import urllib2
import re
from xbmcswift2 import Plugin
from BeautifulSoup import BeautifulSoup

plugin = Plugin()
mixtapepage = plugin.get_storage('mixtapepage', TTL=120)

@plugin.route('/')
def index():
 
	categories = parse_categories()
	mixtapepage.update({'page': 0})
	items = [{
		'label': li.find('a').contents[0].strip(),
		'path': plugin.url_for('show_category', url='http://www.mixtapepage.com/' + li.find('a')['href'].strip(), pnum = '0'),
		} for li in categories]

	return items

@plugin.route('/category/<url>/<pnum>/')
def show_category(url,pnum):
	page = urllib2.urlopen(url)
	soup = BeautifulSoup(page)
	thumbnails = part_thumbnails(soup)
	category_titles = parse_category_titles(soup)	
	category_links = parse_category_links(soup)
	pages = numberof_pages(soup)

	#if pages != 0:
	#	mixtapepage['page'] += 1
	if pages > 0:
		pnum = int(pnum) + 1
		pnum = str(pnum)
	items = [{
		'label': title.find('h2').contents[0].strip(),
		'label2': title.find('h2').contents[0].strip(),
		'icon': 'http://www.mixtapepage.com/' + thumbnail, 
		'thumbnail' : 'http://www.mixtapepage.com/' + thumbnail,  
		'path': 'http://www.mixtapepage.com/' + a, 
		'is_playable': True,
		} for title, a, thumbnail in zip(category_titles, category_links,thumbnails)]
	if mixtapepage['page'] <= pages:
		items.append({
			'label': 'Next Page',
			'label2':'Next Page',
			'path': plugin.url_for('show_category', url= url.replace("http://www.mixtapepage.com/index.php?","http://www.mixtapepage.com/index.php?page=" + pnum +"&"), pnum = pnum), 
			})
	return plugin.finish(items)



def parse_categories():
	page = urllib2.urlopen("http://www.mixtapepage.com/index.php")
	soup = BeautifulSoup(page)
	categories = soup.findAll('li')
	return categories

def remove_dups(seq, idfun=None): 
	# order preserving
	if idfun is None:
		def idfun(x): return x
	seen = {}
	result = []
	for item in seq:
		marker = idfun(item)
		if marker in seen:continue
		seen[marker] = 1
		result.append(item)
	return result


def parse_category_titles(soup):
	titles = soup.findAll('td',attrs={'width' :'70%'})
	return titles

def parse_category_links(soup):
	links = soup.findAll('a',href=True)
	cleanLinks =[]
	for a in links:
		if a['href'].startswith("played.php?id="):
			cleanLinks.append(a['href'])
	cleanLinks = remove_dups(cleanLinks)
	return cleanLinks

def part_thumbnails(soup):
	images = soup.findAll('img',src=True)
	imgsrc = []
	sep ="&sizex"
	for img in images:
		if img['src'].startswith("thumb"):
			img['src'] = img['src'].split(sep, 1)[0]
			img['src'] = img['src'].replace("thumb.php?file=","")
			imgsrc.append(img['src'])
	return imgsrc

def numberof_pages(soup):
	paginator = soup.findAll('option')
	sep1 = "\">"
	sep2 ="value=\""
	temp = []
	remove_dups(paginator)
	for page in paginator:
		if str(page).startswith("<option value=\""):
			popper = page
			popper = str(popper).split(sep1, 1)[0]
			popper = popper.split(sep2, 1)[1]
			popper = popper.replace("\" selected=\"selected","")
			popper = popper.replace("featured.php","")
			if popper.startswith("index.php?") == False:
				temp.append(popper)
	pages = temp.pop()
	return int(pages)

if __name__ == '__main__':
	plugin.run()
